from django.core.paginator import Paginator
from django.http import HttpResponseNotFound
from django.shortcuts import render, redirect,HttpResponse
from django.urls import reverse
from django.views import View
from django.db.models import F
import logging

from album.models import AlbumInfo
from boke import constants
from boke.constants import *
from utils.json_res import json_response
from utils.plot import pie_set
from .models import ArticleInfo, ArticleTag, Comment

logger = logging.getLogger('django')

# Create your views here.
def index(request):
    """
        新闻首页视图
        url: /
        :param request:
        :return:
        """
    # 文章
    news_queryset = ArticleInfo.objects.values('id', 'title', 'content', 'articlephoto', 'reading',
                                               'update_time', ).annotate(
        tag_name=F('article_tag__tag'), author=F('author__username'))
    # 过滤
    news = news_queryset.filter(is_delete=False)
    # 分页
    ArticleList = Paginator(news, PER_PAGE_NEWS_COUNT)
    Articles = ArticleList.page(1)
    # 分类
    tags = ArticleTag.objects.only('id', 'tag').filter(is_delete=False)
    tagList = Paginator(tags, TADGS_PAGE_WALL_COUNT)
    taglists = tagList.page(1)
    # 图片
    albumList = AlbumInfo.objects.all()
    # 进行分页处理
    paginators = Paginator(albumList, ALBUM_PAGE_WALL_COUNT)
    paginator_s = paginators.page(1)
    # 评论
    Comments_page_LIST = Comment.objects.filter(is_delete=False)
    Commentss = Paginator(Comments_page_LIST, COMMENTS_PAGE_WALL_COUNT)
    Comments = Commentss.page(1)
    tags = ArticleTag.objects.only('id', 'tag').filter(is_delete=False)
    return render(request, 'article.html', locals())


class NewsListView(View):
    """
    新闻列表视图
    url: /news/
    args: tag, page
    """

    def get(self, request):
        try:
            # 获取参数
            tag_id = int(request.GET.get('tag', 0))
        except Exception as e:
            logger.error('标签错误：\n{}'.format(e))
            tag_id = 0

        try:
            page = int(request.GET.get('page', 0))
        except Exception as e:
            logger.error('页码错误：\n{}'.format(e))
            page = 1
        # 使用only返回的是对象，所以传递到前端时需要迭代处理
        # values 返回字典
        news_queryset = ArticleInfo.objects.values('id', 'title', 'content', 'articlephoto', 'reading','update_time',).annotate(
            tag_name=F('article_tag__tag'), author=F('author__username'))
        # 过滤
        news = news_queryset.filter(is_delete=False, article_tag=tag_id) or news_queryset.filter(is_delete=False)
        # 分页
        paginator = Paginator(news, constants.PER_PAGE_NEWS_COUNT)
        # 获取页面数据 get_page可以容错
        news_info = paginator.get_page(page)

        data = {
            # 总页数
            'total_pages': paginator.num_pages,
            #
            'news': list(news_info)
        }
        return json_response(data=data)

class NewDetailView(View):
    '''
    文章详情页
    '''
    def get(self, request, news_id):
        news_s = ArticleInfo.objects.prefetch_related('article_tag').only('title', 'content', 'articlephoto', 'reading','update_time','article_tag__tag','author__username').filter(
            is_delete=False, id=news_id).first()
        reading_update = ArticleInfo.objects.filter(is_delete=False, id=news_id).update(reading=F('reading') + 1)
        #评论
        page_comment=Comment.objects.filter(is_delete=False,article_id=news_id)
        # 文章
        news_queryset = ArticleInfo.objects.values('id', 'title', 'content', 'articlephoto', 'reading',
                                                   'update_time', ).annotate(
            tag_name=F('article_tag__tag'), author=F('author__username'))
        # 过滤
        news = news_queryset.filter(is_delete=False)
        # 分页
        ArticleList = Paginator(news, PER_PAGE_NEWS_COUNT)
        Articles = ArticleList.page(1)
        # 分类
        tags = ArticleTag.objects.only('id', 'tag').filter(is_delete=False)
        tagList = Paginator(tags, TADGS_PAGE_WALL_COUNT)
        taglists = tagList.page(1)
        # 图片
        albumList = AlbumInfo.objects.all()
        # 进行分页处理
        paginators = Paginator(albumList, ALBUM_PAGE_WALL_COUNT)
        paginator_s = paginators.page(1)
        # 评论
        Comments_page_LIST = Comment.objects.filter(is_delete=False)
        Commentss = Paginator(Comments_page_LIST, COMMENTS_PAGE_WALL_COUNT)
        Comments = Commentss.page(1)
        if news_s:
            return render(request, 'post.html', locals())
        else:
            return HttpResponseNotFound('<h1>Page not found</h1>')

    def post(self,request,news_id):
         commentator=request.POST.get('name')
         content=request.POST.get('message')
         print(commentator,content)
         comments=Comment(commentator=commentator,content=content,article_id=news_id)
         comments.save()
         return redirect(reverse('Article:news_detail',args=[news_id]))


#后台管理分析图绘制：
def pie_chart(request):
    #获取所有分类标签下面的内容
    tag=ArticleTag.objects.only('id', 'tag').filter(is_delete=False)
    li=list()
    for i in tag:
        item=dict()
        item['tag']=i.tag
        item['count']=ArticleInfo.objects.filter(article_tag__id=i.id).count()
        li.append(item)
    html=pie_set(li)
    return render(request,html)
